#include "air780_controller.h"
#include "uart_driver.h"
#include "freertos/task.h"

static void rx_handler(const char* data, size_t len) {
    // 这里实现AT响应处理状态机
    static char resp_buf[512];
    static size_t resp_len = 0;
    
    memcpy(resp_buf + resp_len, data, len);
    resp_len += len;
    
    if (strstr(resp_buf, "OK") || strstr(resp_buf, "ERROR")) {
        // 触发信号量通知AT指令完成
        resp_len = 0;
    }
}

bool air780_init() {
    uart_init(UART_NUM_1, GPIO_NUM_17, GPIO_NUM_18, 115200);
    uart_set_rx_callback(rx_handler);
    
    const char* init_cmds[] = {
        "AT",
        "AT+CPIN?",
        "AT+CSQ"
    };
    
    for (int i = 0; i < sizeof(init_cmds)/sizeof(init_cmds[0]); i++) {
        if (!uart_send(init_cmds[i], strlen(init_cmds[i]))) {
            return false;
        }
        vTaskDelay(pdMS_TO_TICKS(500));
    }
    return true;
}

bool air780_connect_network() {
    const char* cmd = at_generate_command("AT+NETOPEN");
    uart_send(cmd, strlen(cmd));
    // 这里应等待信号量确认连接成功
    return true;
}
